#!/usr/bin/env bash
# Summary: Display prefix for a Go version
# Usage: goenv prefix [<version>]
#
# Displays the directory where a Go version is installed. If no
# version is given, `goenv prefix' displays the location of the
# currently selected version.

set -e
[ -n "$GOENV_DEBUG" ] && set -x

# Provide goenv completions
if [ "$1" = "--complete" ]; then
  echo system
  exec goenv-versions --bare
fi

versions() {
  goenv versions --bare | $(type -p ggrep grep | head -1) -F "$query" || true
}

latest_version() {
  versions | grep -oE "^$1\\.([0-9]+)?$" | tail -1
}

if [ -n "$1" ]; then
  OLDIFS="$IFS"
  {
    IFS=:
    export GOENV_VERSION="$*"
  }
  IFS="$OLDIFS"
elif [ -z "$GOENV_VERSION" ]; then
  GOENV_VERSION="$(goenv-version-name)"
fi

GOENV_PREFIX_PATHS=()
OLDIFS="$IFS"
{
  IFS=:
  for version in ${GOENV_VERSION}; do
    if [ "$version" = "system" ]; then
      if GO_PATH="$(GOENV_VERSION="${version}" goenv-which go 2>/dev/null)"; then
        GOENV_PREFIX_PATH="${GO_PATH%/bin/*}"
      else
        echo "goenv: system version not found in PATH" >&2
        exit 1
      fi
    else
      if grep -q -E "^[0-9]+\.[0-9]+(\s*)$" <<<${version}; then
        REGEX=$(echo $version | sed s/\\./\\\\./)
        LATEST_PATCH=$(latest_version $REGEX)
        echo "Using latest patch version $LATEST_PATCH"
        version=$LATEST_PATCH
      fi

      GOENV_PREFIX_PATH="${GOENV_ROOT}/versions/${version}"
    fi
    if [ -d "$GOENV_PREFIX_PATH" ]; then
      GOENV_PREFIX_PATHS=("${GOENV_PREFIX_PATHS[@]}" "$GOENV_PREFIX_PATH")
    else
      echo "goenv: version '${version}' not installed" >&2
      exit 1
    fi
  done
}
IFS="$OLDIFS"

OLDIFS="$IFS"
{
  IFS=:
  echo "${GOENV_PREFIX_PATHS[*]}"
}
IFS="$OLDIFS"
